<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;

/**
 * Created by PhpStorm.
 * User: shiding
 * Date: 2019-06-25
 * Time: 19:37
 */
class UploadService
{
    const SUCCESS_STATUS = 0;
    const ERROR_STATUS = 1;
    const FILE_ERROR_STATUS = 1001;

    protected $message = [
        self::SUCCESS_STATUS => "上传成功",
        self::ERROR_STATUS => "上传失败",
        self::FILE_ERROR_STATUS => "未知文件路径,上传失败"
    ];

    public function upload($file)
    {
        $disk = Storage::disk('qiniu');
        $extension = $file->extension();
        $fileName = date("Ymd") . '_' .  str_random(6) . '.' . $extension;
        $path = $file->path();
        if (!isset($path)) {
            return $this->returnData(self::FILE_ERROR_STATUS);
        }
        $result = $disk->put($fileName, file_get_contents($file->getRealPath()));
        return $this->returnData(
            $result ? self::SUCCESS_STATUS : self::ERROR_STATUS,
            $result ? $fileName : ''
        );
    }

    public function returnData($status, $data = "")
    {
        return $data
            ? ["status" => $status, "msg" => $this->message[$status], "data" => $data]
            : ["status" => $status, "msg" => $this->message[$status]];
    }
}